class Solution 
{
public:
    bool wordPattern(string pattern, string s) 
    {
        unordered_map<string, char> str2ch;
        unordered_map<char, string> ch2str;

        int str_len = s.size();
        int ptr2ch_start = 0;
        for(size_t i = 0; i < pattern.size(); i++)  // 遍历匹配模板
        {
            if (ptr2ch_start >= str_len)                  // 模板未匹配完成，字符串已用尽
            {
                return false;
            }

            int ptr2ch_end = ptr2ch_start;
            while (ptr2ch_end < str_len && s[ptr2ch_end] != ' ') 
            {
                ptr2ch_end++;
            }
            const string& temp = s.substr(ptr2ch_start, ptr2ch_end - ptr2ch_start);

            if (str2ch.count(temp) && str2ch[temp] != pattern[i])
            {
                return false;
            }

            if (ch2str.count(pattern[i]) && ch2str[pattern[i]] != temp)
            {
                return false;
            }

            str2ch[temp] = pattern[i];
            ch2str[pattern[i]] = temp;
            ptr2ch_start = ptr2ch_end + 1;
        }
        return ptr2ch_start >= str_len;
    }
};